package com.example.demo_test.Config;

import com.example.demo_test.Dao.GroupDao;
import com.example.demo_test.Dao.MessageDao;
import com.example.demo_test.Dao.PersonDao;
import com.example.demo_test.Service.MessageService;
import com.example.demo_test.Service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author zhanghong
 * @date 2021/5/17  0017 18:16
 */
@Component
public class TimedTask {
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private GroupDao groupDao;
    @Autowired
    private PersonDao personDao;
    @Value( "${prop.upload-folder}" )
    private String uploadPath;
    @Scheduled(fixedRate = 86400000)
    /**
     * @author zhanghong
     * @description 定时处理预期未缴纳用户
     * @method-name handelFine
     * @date 2021-06-04 17:48
     * @param
     * @return void
     */
    public void handelDelete(){
        System.out.println(new Date()+" 执行了删除");
        messageDao.deleteMessage();
    }

    @Scheduled(fixedRate = 86400000)
    public void deleteFile(){
        System.out.println( "执行了清理无用头像" );
        List<String> avatarList=personDao.getUserAvatarPathList();
        avatarList.addAll( groupDao.getGroupAvatarPath() );
        File file =new File(uploadPath);
        File[] files=file.listFiles();
        for (File fd:files
             ) {
            if(!avatarList.contains(fd.getName().replaceAll( uploadPath,"" )) && !fd.getName().replaceAll( uploadPath,"" ).equals("test.jpg")){
                fd.delete();
            }
        }

    }




    //3.添加定时任务
    //@Scheduled(cron = "0/5 * * * * ?")
    //或直接指定时间间隔，例如：5秒
    @Scheduled(fixedRate=58*1000)
    private void configureTasks() throws Exception{
        System.out.println("心跳");
        WebSocketService.sendMessageForHeartbeat();
    }
}
